#include "head.h"

int localNetFdSend(int net_fd,int flag, int local_socket_fd){


        struct msghdr msg;
        bzero(&msg, sizeof(msg));

        struct iovec iovs[1];
        iovs[0].iov_base = &flag;
        iovs[0].iov_len = sizeof(flag);

        msg.msg_iov = iovs;
        msg.msg_iovlen = 1;

        struct cmsghdr * cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
        cms->cmsg_len = CMSG_LEN(sizeof(int));
        cms->cmsg_level = SOL_SOCKET;
        cms->cmsg_type = SCM_RIGHTS;
        void *p = CMSG_DATA(cms);
        int *pfd = (int *)p;
        *pfd = net_fd;
        

        msg.msg_control = cms;
        msg.msg_controllen = CMSG_LEN(sizeof(int));

        // 发送数据
        int ret = sendmsg(local_socket_fd, &msg, 0);
        ERROR_CHECK(ret, -1, "sendmsg");
    return 0;
}

int localNetFdRecv(int *net_fd, int *flag,int local_socket_fd){
        struct msghdr msg;
        bzero(&msg, sizeof(msg));

        int *pFalg = (int *)malloc(sizeof(int)); 
        struct iovec iovs[1];
        iovs[0].iov_base = pFalg;
        iovs[0].iov_len = sizeof(int);

        msg.msg_iov = iovs;
        msg.msg_iovlen = 1;

        struct cmsghdr * cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
        cms->cmsg_len = CMSG_LEN(sizeof(int));
        cms->cmsg_level = SOL_SOCKET;
        cms->cmsg_type = SCM_RIGHTS;
        
        msg.msg_control = cms;
        msg.msg_controllen = CMSG_LEN(sizeof(int));
        
        int ret = recvmsg(local_socket_fd, &msg, 0);
        ERROR_CHECK(ret, -1, "recvmsg");

        void *p = CMSG_DATA(cms);
        int *p_net_fd = (int *)p;
        *net_fd = *p_net_fd;


        *flag = *pFalg;

    return 0;
}
